from flask import Flask, request, json, make_response
import mongo_
import argparse

from handle_logic import Logic

app = Flask(__name__)

parser = argparse.ArgumentParser()
parser.add_argument("-ip")
parser.add_argument("-P1")
parser.add_argument("-P5")

args = parser.parse_args()

if args.ip:
    print("123")
    RUN1_IP = args.ip
    RUN1_PORT = args.P1
    RUN5_PORT = args.P5

else:
    RUN1_IP = "192.168.1.43"
    RUN1_PORT = 61002
    RUN5_PORT = 61010


def mkresp(obj):
    # 跨域问题
    resp = make_response(json.dumps(obj))
    resp.headers["Access-Control-Allow-Origin"] = "*"
    resp.headers["Access-Control-Allow-Methods"] = "GET,POST"
    resp.headers["Access-Control-Allow-Headers"] = "x-requested-with,content-type"  # 预检请求  该次请求的自定义请求头字段
    return resp


# 返回档案的id列表
@app.route("/inquiry", methods=["POST"])
def inquiry():
    try:
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))
        picture_image = json_data.get("picture_image")
        similarity = json_data.get("similarity")
        start_time = json_data.get("start_time")
        end_time = json_data.get("end_time")
        camera_id = json_data.get("camera_id")

        data_info = {}

        if similarity is not None:
            if not isinstance(similarity, int):
                raise Exception
            if similarity < 0 or similarity > 100:
                raise Exception

        if similarity is None:
            similarity = 0

        if start_time is not None:
            if not isinstance(start_time, int):
                raise Exception
            if data_info.get("timestamp"):
                data_info.get("timestamp").update({"$gte": start_time})
            if not data_info.get("timestamp"):
                data_info.update({"timestamp": {"$gte": start_time}})

        if end_time is not None:
            if not isinstance(end_time, int):
                raise Exception
            if data_info.get("timestamp"):
                data_info.get("timestamp").update({"$lte": end_time})
            if not data_info.get("timestamp"):
                data_info.update({"timestamp": {"$lte": end_time}})

        if camera_id is not None:
            if not isinstance(camera_id, str):
                raise Exception
            data_info.update({"camera_id": camera_id})

        if not isinstance(picture_image, str):
            raise Exception

    except Exception:
        return mkresp({"msg": "Parameter error", "rtn": -3})

    try:
        res_data = quiry_logic.acvs_p(data_info=data_info, similarity=similarity, picture_image=picture_image)
        print(res_data)

    except Exception as e:
        return mkresp({"msg": str(e), "rtn": -3})

    return mkresp({"msg": "OK", "rtn": 0, "data": res_data})


def init():
    global mongo_host, mongo_port, stranger_limit, card_limit

    # mongo_host = mongoinfo['ip']
    # mongo_port = mongoinfo['port']
    mongo_host = "192.168.1.43"
    mongo_port = 61000
    stranger_limit = guidanginfo['face_limit']
    card_limit = guidanginfo['card_limit']

    global mongo_client, quiry_logic
    mongo_client = mongo_.MyMongoClient(host=mongo_host, port=mongo_port, server_port=RUN1_PORT, ip=RUN1_IP)

    quiry_logic = Logic(mongo_client=mongo_client, stranger_limit=stranger_limit, card_limit=card_limit)


if __name__ == "__main__":
    with open('../config.py', 'r', encoding="utf-8") as conf_r:
        print(conf_r)
        exec(conf_r.read())
    init()
    app.run(host="0.0.0.0", port=RUN5_PORT, debug=False)
